<?php
namespace app\api\service;

use app\api\model\Order as OrderModel;
use app\api\service\Order as OrderService;
use app\api\model\Product;
use app\lib\enum\OrderStatusEnum;
use think\Loader;
use think\Log;
use think\Exception;
use think\Db;

Loader::import('Wxpay.WxPay',EXTEND_PATH,'.Api.php');
class WxNotify extends \WxPayNotify{
	
	public function NotifyProcess($data,&$msg){
		if($data['result_code'] == 'SUCCESS'){

			$orderNo = $data['out_trade_no'];
			// 开启事务
			Db::startTrans();
			try{
				// 查询加锁
				$order = OrderModel::where('order_no','=',$orderNo)->lock(true)->find();
				if($order->status == 1){
					$service = new OrderService();
					$stockStatus = $service->checkOrderStock($order->id);
					if($stockStatus['pass']){
						$this->updateOrderStatus($order->id,true);//修改订单状态
						$this->reduceStock($stockStatus);//减库存
					}else{
						// 已支付，但库存不足
						$this->updateOrderStatus($order->id,false);//修改订单状态
					}
				}
				Db::commit();
				return true;
			}catch(Exception $ex){
				Db::rollback();
				Log::error($ex);
				return false;
			}
		}else{
			// 微信支付失败
			return true;// 只是用来控制微信是否继续发送
		}
	}

	private function updateOrderStatus($orderID,$success){
		$status = $success ? OrderStatusEnum::PAID : OrderStatusEnum::PAID_BUT_OUT_OF;

		OrderModel::where('id','=',$orderID)->update(['status'=>$status]);

	}

	private function reduceStock($stockStatus){
		foreach ($stockStatus['pStatusArray'] as $singlePStatus){
			Product::where('id','=',$singlePStatus['id'])->setDec('stock',$singlePStatus['count']);
		}
	}

}
?>